package com.caifu.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caifu.bean.PageDo;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.controller.AbstractController;
import com.caifu.enums.LabelTypeEnum;
import com.caifu.enums.ShopPropertyEnum;
import com.caifu.excel.shopExcel.ExcelYsShop;
import com.caifu.excel.shopExcel.ExcelYsShopError;
import com.caifu.mapper.*;
import com.caifu.pojo.*;
import com.caifu.util.AesUtil;
import com.caifu.util.CheckIdCardUtil;
import com.caifu.util.CheckUtil;
import com.caifu.util.TreeUtils;
import com.caifu.vo.ReportRecordPageVO;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

/**
 * ClassName : ReportRecordService
 *
 * @author :  yb
 * @description ：
 * @date : 2021-03-01 16:50
 */
@Service
public class ReportRecordService extends AbstractController {

    @Resource
    private YsShopReportRecordMapper ysShopReportRecordMapper;

    @Resource
    private YsShopReportRecordLogMapper ysShopReportRecordLogMapper;

    @Resource
    private SysOrganizationMapper sysOrganizationMapper;

    @Resource
    private YsShopMapper ysShopMapper;

    @Resource
    private YsLabelMapper ysLabelMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 判断表头是否一致
     */
    private boolean isTrueHead = true;

    /**
     * 导入 商铺 报表
     *
     * @param file       报表文件
     * @param addOrCover 增加或者覆盖 1-增加 2-覆盖
     * @return Result
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<Object> importShopReport(MultipartFile file, Integer addOrCover) throws Exception {

        //经营业态
        List<YsLabel> businessTypeList = getLabelListByParentId(LabelTypeEnum.JYYT.getKey());
        //经营状态
        List<YsLabel> managementStatusList = getLabelListByParentId(LabelTypeEnum.JYZT.getKey());
        //商铺标签
        List<YsLabel> shopTypeList = getLabelListByParentId(LabelTypeEnum.SPBQ.getKey());
        //所有组织架构
        List<SysOrganization> allSysOrganization = getAllSysOrganization();
        //获取 (商铺名称+门牌地址) 判断是否唯一
        List<String> shopNameAndAddressList = getShopNameAndAddressList();

        //读取excel中的数据
        List<ExcelYsShop> excelYsShopList = readExcel(file);

        if (excelYsShopList.size() <= 0) {
            return ResultUtil.errorMsg("请不要导入空文件");
        }
        if (!isTrueHead) {
            return ResultUtil.errorMsg("表头与模板不一致,请上传正确文件");
        }
        //设置序列号
        setSort(excelYsShopList);

        //保存的ysShop
        List<YsShop> saveYsShopList = new ArrayList<>();
        //成功
        List<YsShopReportRecordLog> saveSuccessLogList = new ArrayList<>();
        //失败
        List<YsShopReportRecordLog> saveFailLogList = new ArrayList<>();

        //报表中的（商铺名称+门牌地址）集合
        List<String> excelShopNameAddAddress = new ArrayList<>();
        excelYsShopList.forEach(excelYsShop -> excelShopNameAddAddress.add(excelYsShop.getShopName() + excelYsShop.getAddress()));


        //校验数据 和 数据处理
        excelYsShopList.forEach(excelYsShop -> {
            //数据校验
            String errorMsg = excelShopDataCheck(excelYsShop, addOrCover, allSysOrganization, shopNameAndAddressList);

            //判断报表中（商铺名称+门牌地址） 是否有重复
            String shopNameAddress = excelYsShop.getShopName() + excelYsShop.getAddress();
            int count = Collections.frequency(excelShopNameAddAddress, shopNameAddress);
            if (count > 1) {
                if (CheckUtil.isNotNull(errorMsg)) {
                    errorMsg += (",报表中(商铺名称+门牌地址)出现重复");
                } else {
                    errorMsg += ("报表中(商铺名称+门牌地址)出现重复");
                }
            }

            //*********** 将数据分别放入不同的集合中 **************
            //errorMsg为空 说明数据校验通过
            try {
                if (CheckUtil.isNull(errorMsg)) {
                    // 如果保存ysShop    数据处理
                    YsShopReportRecordLog successLog = getReportRecordLog(excelYsShop, errorMsg, 1);
                    saveSuccessLogList.add(successLog);
                    transformForDataExcelShopInfo(excelYsShop, businessTypeList, managementStatusList, shopTypeList, allSysOrganization);

                    YsShop addYsShop = getYsShop(excelYsShop);
                    saveYsShopList.add(addYsShop);
                } else {
                    //错误日志  state //1-成功 9-失败
                    YsShopReportRecordLog failLog = getReportRecordLog(excelYsShop, errorMsg, 9);
                    saveFailLogList.add(failLog);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

        //***********保存ysShop , report_record_log, report_record **************
        String importResult = "成功导入" + saveSuccessLogList.size() + "数据,失败" + saveFailLogList.size() + "笔";

        //保存报表记录  getSysUser()
        YsShopReportRecord reportRecord = getYsReportRecord(file.getOriginalFilename(), importResult, getSysUser());
        ysShopReportRecordMapper.insert(reportRecord);

        //放入报表的id
        saveSuccessLogList.forEach(successMsReportLog -> successMsReportLog.setReportId(reportRecord.getId()));
        saveFailLogList.forEach(failMsReportLog -> failMsReportLog.setReportId(reportRecord.getId()));

        //保存成功和错误日志
        saveSuccessLogList.forEach(successMsReportLog -> ysShopReportRecordLogMapper.insert(successMsReportLog));
        saveFailLogList.forEach(failMsReportLog -> ysShopReportRecordLogMapper.insert(failMsReportLog));

        //保存商铺 -增加或者覆盖
        saveShopList(saveYsShopList, addOrCover);

        return ResultUtil.success(200, importResult);
    }

    /**
     * 保存  Excel中的 店铺信息
     *
     * @param saveYsShopList saveYsShopList
     * @param addOrCover     增加或者覆盖 1-增加 2-覆盖
     */
    private void saveShopList(List<YsShop> saveYsShopList, Integer addOrCover) {
        int addNum = 1;
        int coverNum = 2;
        saveYsShopList.forEach(shop -> {
            //新增
            if (addNum == addOrCover) {
                shop.setCreateUserId(getSysUser().getId());
                ysShopMapper.insert(shop);
            } else if (coverNum == addOrCover) {
                //覆盖
                QueryWrapper<YsShop> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("shop_name", shop.getShopName());
                queryWrapper.eq("address", shop.getAddress());
                YsShop oldShop = ysShopMapper.selectOne(queryWrapper);

                //如果(店铺名称+地址) 唯一标识存在  覆盖 否则添加
                if (CheckUtil.isNotNull(oldShop)) {
                    shop.setId(oldShop.getId());
                    ysShopMapper.updateById(shop);
                } else {
                    ysShopMapper.insert(shop);
                }
            }
        });

    }


    /**
     * 报表数据 转成 YsShop 对象
     *
     * @param excelYsShop excelYsShop
     * @return YsShop
     */
    private YsShop getYsShop(ExcelYsShop excelYsShop) {
        YsShop ysShop = new YsShop();
        ysShop.setCreateTime(new Date());
        ysShop.setState(1);
        //shop_type 商铺标签
        ysShop.setShopType(excelYsShop.getLabel());
        BeanUtils.copyProperties(excelYsShop, ysShop);
        return ysShop;
    }

    /**
     * @param excelYsShop          excelYsShop
     * @param businessTypeList     经营业态
     * @param managementStatusList 经营状态
     * @param shopTypeList         商铺标签
     * @param allSysOrganization   所有组织架构
     */
    private void transformForDataExcelShopInfo(ExcelYsShop excelYsShop, List<YsLabel> businessTypeList
            , List<YsLabel> managementStatusList, List<YsLabel> shopTypeList, List<SysOrganization> allSysOrganization) throws Exception {

        //经营业态
        if (CheckUtil.isNotNull(excelYsShop.getBusinessType())) {
            String labelId = getLabelIds(businessTypeList, excelYsShop.getBusinessType());
            excelYsShop.setBusinessType(CheckUtil.isNull(labelId) ? "" : labelId);
        }
        //经营状态
        if (CheckUtil.isNotNull(excelYsShop.getManagementStatus())) {
            String labelId = getLabelIds(managementStatusList, excelYsShop.getManagementStatus());
            excelYsShop.setManagementStatus(CheckUtil.isNull(labelId) ? "" : labelId);
        }
        //商铺标签
        if (CheckUtil.isNotNull(excelYsShop.getLabel())) {
            String labelId = getLabelIds(shopTypeList, excelYsShop.getLabel());
            excelYsShop.setLabel(CheckUtil.isNull(labelId) ? "" : labelId);
        }
        //所有组织架构
        if (CheckUtil.isNotNull(excelYsShop.getOrgId())) {
            allSysOrganization.forEach(model -> {
                if (model.getName().equals(excelYsShop.getOrgId())) {
                    excelYsShop.setOrgId(model.getId() + "");
                }
            });
        }

        //身份证
        if (CheckUtil.isNotNull(excelYsShop.getUserPid())) {
            excelYsShop.setUserPid(AesUtil.Encrypt(excelYsShop.getUserPid()));
        }
        //手机号
        if (CheckUtil.isNotNull(excelYsShop.getPhone())) {
            excelYsShop.setPhone(AesUtil.Encrypt(excelYsShop.getPhone()));
        }
        //产权人身份证
        if (CheckUtil.isNotNull(excelYsShop.getPropertyUserPid())) {
            excelYsShop.setPropertyUserPid(AesUtil.Encrypt(excelYsShop.getPropertyUserPid()));
        }
        //商铺产权 商铺产权 1-个人 2-企业
        if (CheckUtil.isNotNull(excelYsShop.getShopProperty())) {
            excelYsShop.setShopProperty(ShopPropertyEnum.getEnumKey(excelYsShop.getShopProperty()));
        }


    }


    /**
     * @param excelYsShop            excelYsShop
     * @param addOrCover             增加或者覆盖 1-增加 2-覆盖
     * @param allSysOrganization     组织架构
     * @param shopNameAndAddressList (商铺名称+门牌地址) 判断是否唯一
     * @return 错误信息
     */
    private String excelShopDataCheck(ExcelYsShop excelYsShop, Integer addOrCover
            , List<SysOrganization> allSysOrganization, List<String> shopNameAndAddressList) {
        StringBuilder errorMsg = new StringBuilder();

        //新增的时候  验证(商铺名称+门牌地址)  和数据库对比 是否重复
        if (1 == addOrCover) {
            checkShopNameAndAddress(errorMsg, excelYsShop, shopNameAndAddressList);
        }

        //商铺名称
        int shopNameMaxSize = 20;
        if (CheckUtil.isNull(excelYsShop.getShopName())) {
            errorMsg.append("商铺名称不能为空,");
        } else if (excelYsShop.getShopName().length() > shopNameMaxSize) {
            errorMsg.append("商铺名称输入过长(长度超过20位字符),");
            //商铺名称过长截取 否则记录表无法保存
            excelYsShop.setShopName(excelYsShop.getShopName().substring(0, 15) + "...");
        }
        //门牌地址
        int addressMaxSize = 50;
        if (CheckUtil.isNull(excelYsShop.getAddress())) {
            errorMsg.append("门牌地址不能为空,");
        } else if (excelYsShop.getAddress().length() > addressMaxSize) {
            errorMsg.append("门牌地址输入过长(长度超过50位),");
            //门牌地址过长截取 否则记录表无法保存
            excelYsShop.setAddress(excelYsShop.getAddress().substring(0, 45) + "...");
        }

        //管辖区域
        int orgMaxSize = 50;
        if (CheckUtil.isNull(excelYsShop.getOrgId())) {
            errorMsg.append("管辖区域不能为空,");
        } else {
            if (excelYsShop.getAddress().length() > orgMaxSize) {
                errorMsg.append("管辖区域输入有误,");
                //管辖区域过长截取 否则记录表无法保存
                excelYsShop.setAddress(excelYsShop.getAddress().substring(0, 45) + "...");
            }

            //末节点的orgId
            String realOrgId = getOrgIdByMatchingOrgName(allSysOrganization, excelYsShop.getOrgId());
            if (CheckUtil.isNull(realOrgId)) {
                errorMsg.append("管辖区域匹配失败,");
            } else if (!TreeUtils.isEndNode(allSysOrganization, Integer.parseInt(realOrgId))) {
                //是否是末节点组织架构
                errorMsg.append("管辖区域需为末节点组织,");
            }
        }

        //经营业态
        if (CheckUtil.isNull(excelYsShop.getBusinessType())) {
            errorMsg.append("经营业态不能为空,");
        }
        //经营状态
        if (CheckUtil.isNull(excelYsShop.getManagementStatus())) {
            errorMsg.append("经营状态不能为空,");
        }
        //店主姓名
        int shopkeeperNameMaxSize = 10;
        if (CheckUtil.isNull(excelYsShop.getShopkeeperName())) {
            errorMsg.append("店主姓名不能为空,");
        } else if (excelYsShop.getShopkeeperName().length() > shopkeeperNameMaxSize) {
            errorMsg.append("店主姓名过长(长度超过10位),");
        }
        //身份证号
        if (CheckUtil.isNotNull(excelYsShop.getUserPid())) {
            if (!CheckIdCardUtil.check(excelYsShop.getUserPid())) {
                errorMsg.append("身份证号输入有误,");
            }
        }
        //手机号
        int telSize = 20;
        if (CheckUtil.isNull(excelYsShop.getPhone())) {
            errorMsg.append("手机号不能为空,");
        } else if (!CheckIdCardUtil.isChinaPhoneLegal(excelYsShop.getPhone())) {
            errorMsg.append("手机号码输入有误,");
            //手机号过长
            if (excelYsShop.getPhone().length() > telSize) {
                excelYsShop.setPhone(excelYsShop.getPhone().substring(0, 15) + "...");
            }
        }
        //从业人数
        if (CheckUtil.isNotNull(excelYsShop.getEmployedNumber())) {
            if (!CheckUtil.isNumeric(excelYsShop.getEmployedNumber() + "")) {
                errorMsg.append("从业人数输入有误,");
            }
        }
        //商铺面积
        if (CheckUtil.isNotNull(excelYsShop.getShopArea())) {
            if (!CheckUtil.isSalaryNumber(excelYsShop.getShopArea() + "")) {
                errorMsg.append("商铺面积输入有误,");
            }
        }
        //开业日期
        String dateFormat = "yyyy-MM-dd";
        if (CheckUtil.isNotNull(excelYsShop.getOpenTime())) {
            if (!CheckUtil.isValidDate(excelYsShop.getOpenTime(), dateFormat)) {
                errorMsg.append("开业日期输入有误,");
            }
        }
        //产权人
        int propertyNameMaxSize = 50;
        if (CheckUtil.isNotNull(excelYsShop.getPropertyName())) {
            if (excelYsShop.getPropertyName().length() > propertyNameMaxSize) {
                errorMsg.append("产权人输入过长(长度超过50位),");
                excelYsShop.setPropertyName(excelYsShop.getPropertyName().substring(0, 45) + "...");
            }
        }
        //产权人身份证号
        if (CheckUtil.isNotNull(excelYsShop.getPropertyUserPid())) {
            if (!CheckIdCardUtil.check(excelYsShop.getPropertyUserPid())) {
                errorMsg.append("产权人身份证号输入有误,");
            }
        }
        //联系方式
        int propertyPhoneMaxSize = 20;
        if (CheckUtil.isNotNull(excelYsShop.getPropertyPhone())) {
            if (excelYsShop.getPropertyPhone().length() > propertyPhoneMaxSize) {
                errorMsg.append("联系方式输入过长(长度超过20位),");
                excelYsShop.setPropertyName(excelYsShop.getPropertyName().substring(0, 15) + "...");
            }
        }
        //标签
        if (CheckUtil.isNotNull(excelYsShop.getLabel())) {
            if (!checkExcelLabel(excelYsShop.getLabel())) {
                errorMsg.append("标签匹配失败,");
            }
        }
        //备注
        int remarkMaxSize = 200;
        if (CheckUtil.isNotNull(excelYsShop.getRemarks())) {
            if (excelYsShop.getRemarks().length() > remarkMaxSize) {
                errorMsg.append("备注输入过长(长度超过200位),");
                excelYsShop.setRemarks(excelYsShop.getRemarks().substring(0, 190) + "...");
            }
        }

        return CheckUtil.isNull(errorMsg.toString()) ? "" : errorMsg.toString().substring(0, errorMsg.toString().length() - 1);
    }


    /**
     * @param excelYsShop excelYsShop
     * @param error       error
     * @param state       state
     * @return MsReportRecordLog
     */
    private YsShopReportRecordLog getReportRecordLog(ExcelYsShop excelYsShop, String error, int state) throws Exception {
        YsShopReportRecordLog recordLog = new YsShopReportRecordLog();
        recordLog.setState(state);
        recordLog.setErrorMessage(error);
        recordLog.setCreateTime(new Date());
        BeanUtils.copyProperties(excelYsShop, recordLog);

        //手机号
        if (CheckUtil.isNotNull(excelYsShop.getPhone())) {
            recordLog.setPhone(AesUtil.Encrypt(excelYsShop.getPhone()));
        }
        //身份证
        if (CheckUtil.isNotNull(excelYsShop.getUserPid())) {
            recordLog.setUserPid(AesUtil.Encrypt(excelYsShop.getUserPid()));
        }
        //产权人身份证
        if (CheckUtil.isNotNull(excelYsShop.getPropertyUserPid())) {
            recordLog.setPropertyUserPid(AesUtil.Encrypt(excelYsShop.getPropertyUserPid()));
        }

        return recordLog;
    }


    /**
     * 验证 excel中的标签 是否和数据库的一致 (商铺标签)
     *
     * @param label label
     * @return boolean
     */
    private boolean checkExcelLabel(String label) {
        List<YsLabel> shopTypeList = getLabelListByParentId(LabelTypeEnum.SPBQ.getKey());
        List<String> shopTypeNameList = new ArrayList<>();
        shopTypeList.forEach(model -> shopTypeNameList.add(model.getLabelName()));

        String[] labelList = label.split(",");
        for (String s : labelList) {
            if (!shopTypeNameList.contains(s)) {
                return false;
            }
        }
        return true;
    }


    /**
     * 新增的时候   验证(商铺名称+门牌地址)  和数据库对比 是否重复
     *
     * @param errorMsg               errorMsg
     * @param excelYsShop            excelYsShop
     * @param shopNameAndAddressList (商铺名称+门牌地址)集合
     */
    private void checkShopNameAndAddress(StringBuilder errorMsg, ExcelYsShop excelYsShop, List<String> shopNameAndAddressList) {
        String str = excelYsShop.getShopName() + excelYsShop.getAddress();
        if (shopNameAndAddressList.contains(str)) {
            errorMsg.append("商铺名称+门牌地址 已存在,");
        }
    }

    /**
     * 判断 组织名称是否跟数据库的匹配
     *
     * @param allSysOrganization allSysOrganization
     * @param orgName            orgName
     * @return boolean
     */
    private String getOrgIdByMatchingOrgName(List<SysOrganization> allSysOrganization, String orgName) {
        String orgId = "";
        if (CheckUtil.isNull(orgName)) {
            return orgId;
        }
        for (SysOrganization org : allSysOrganization) {
            if (org.getName().equals(orgName)) {
                orgId = String.valueOf(org.getId());
                break;
            }
        }
        return orgId;
    }


    /**
     * 报表记录对象
     */
    private YsShopReportRecord getYsReportRecord(String fileName, String importResult, SysUser sysUser) {
        YsShopReportRecord shopReportRecord = new YsShopReportRecord();
        shopReportRecord.setReportName(fileName);
        shopReportRecord.setImportResult(importResult);
        //操作人员
        if (CheckUtil.isNotNull(sysUser)) {
            shopReportRecord.setOperationUserId(sysUser.getId());
        }
        //小区编号

        shopReportRecord.setCreateTime(new Date());
        return shopReportRecord;
    }


    /**
     * 读取数据
     */
    private List<ExcelYsShop> readExcel(MultipartFile file) throws Exception {
        List<ExcelYsShop> excelYsShopList = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), ExcelYsShop.class, new AnalysisEventListener<ExcelYsShop>() {

            @Override
            public void invoke(ExcelYsShop excelYsShop, AnalysisContext analysisContext) {
                excelYsShopList.add(excelYsShop);
            }

            @Override
            public void invokeHeadMap(Map headMap, AnalysisContext context) {
                isTrueHead = isExcelHead(JSONObject.fromObject(JSON.toJSONString(headMap)));
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            }
        }).sheet().doRead();
        return excelYsShopList;
    }

    /**
     * 判断表头是否正确
     *
     * @param jsonObject 获取的表头
     */
    private Boolean isExcelHead(JSONObject jsonObject) {
        //表头 -为了验证表头是否一致
        String[] shopExcelHeader = new String[]{"*商铺名称", "*门牌地址", "*管辖区域", "*经营业态", "*经营状态"
                , "*姓名", "身份证号", "*手机号", "从业人数(填纯数字)", "商铺面积(单位:平方米,例:88.08)", "开业时间(例:1988-05-18)"
                , "商铺产权", "产权人姓名", "身份证号", "联系电话", "标签(根据批注进行选择,多个英文逗号隔开)", "备注"};

        for (int i = 0; i < shopExcelHeader.length; i++) {
            if (!shopExcelHeader[i].equals(jsonObject.get(i + ""))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 排序
     */
    private void setSort(List<ExcelYsShop> excelYsShopList) {
        int sort = 1;
        for (ExcelYsShop excelYsShop : excelYsShopList) {
            excelYsShop.setSort(sort);
            sort++;
        }
    }


    /**
     * 获取所有组织架构
     */
    private List<SysOrganization> getAllSysOrganization() {
        QueryWrapper<SysOrganization> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "1");
        return sysOrganizationMapper.selectList(queryWrapper);

    }

    /**
     * 获取 商铺名称+门牌地址
     *
     * @return List
     */
    private List<String> getShopNameAndAddressList() {
        QueryWrapper<YsShop> queryWrapper = new QueryWrapper<>();
        //状态 1-有效 2-关闭 9-删除
        queryWrapper.eq("state", "1").or().eq("state", "2");
        List<YsShop> ysShops = ysShopMapper.selectList(queryWrapper);

        List<String> list = new ArrayList<>();
        ysShops.forEach(ysShop -> list.add(ysShop.getShopName() + ysShop.getAddress()));
        return list;
    }

    /**
     * 获取标签 集合
     *
     * @param pId 父类id
     * @return List
     */
    public List<YsLabel> getLabelListByParentId(String pId) {
        QueryWrapper<YsLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", pId);
        queryWrapper.eq("status", "1");
        queryWrapper.orderByDesc("created_time");
        return ysLabelMapper.selectList(queryWrapper);
    }


    /**
     * @param parentCode parentCode
     * @return MsLabel  Array
     */
    public String[] getLabelNameArray(String parentCode) {
        List<YsLabel> msLabelList = getLabelListByParentId(parentCode);
        List<String> labelNameList = new ArrayList<>();
        msLabelList.forEach(model -> labelNameList.add(model.getLabelName()));
        return labelNameList.toArray(new String[0]);
    }


    /**
     * 标签类型 name 转成code
     *
     * @param labelList  labelList
     * @param labelNames labelNames
     * @return String
     */
    String getLabelIds(List<YsLabel> labelList, String labelNames) {
        String[] arr = labelNames.split(",");
        String labelCodes = "";
        for (String s : arr) {
            if (CheckUtil.isNotNull(s)) {
                for (YsLabel label : labelList) {
                    if (label.getLabelName().equals(s)) {
                        if (CheckUtil.isNotNull(labelCodes)) {
                            labelCodes += "," + label.getId();
                        } else {
                            labelCodes += label.getId();
                        }
                    }
                }
            }
        }
        return labelCodes;
    }

    /**
     * 获取原始报表数据
     *
     * @param reportId reportId 报表 id
     * @return List
     */
    public List<ExcelYsShop> getOriginalExcelUserInfo(Integer reportId) {
        List<ExcelYsShop> excelYsShopList = new ArrayList<>();
        List<YsShopReportRecordLog> logList = getReportRecordLogList(reportId, 1);
        logList.forEach(log -> {
            ExcelYsShop excelYsShop = new ExcelYsShop();
            //解密手机号 和证件号
            aesMyUtilDecrypt(log);
            BeanUtils.copyProperties(log, excelYsShop);
            excelYsShopList.add(excelYsShop);
        });
        return excelYsShopList;
    }

    /**
     * 解密手机号 和证件号
     *
     * @param log ReportRecordLog
     */
    private void aesMyUtilDecrypt(YsShopReportRecordLog log) {
        try {
            if (CheckUtil.isNotNull(log.getPhone())) {
                log.setPhone(AesUtil.Decrypt(log.getPhone()));
            }
            if (CheckUtil.isNotNull(log.getUserPid())) {
                log.setUserPid(AesUtil.Decrypt(log.getUserPid()));
            }
            if (CheckUtil.isNotNull(log.getPropertyUserPid())) {
                log.setPropertyUserPid(AesUtil.Decrypt(log.getPropertyUserPid()));
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }


    /**
     * 获取日志集合
     *
     * @param reportId 报表 id
     * @return List
     */
    private List<YsShopReportRecordLog> getReportRecordLogList(Integer reportId, Integer state) {
        QueryWrapper<YsShopReportRecordLog> reportRecordLogQueryWrapper = new QueryWrapper<>();
        reportRecordLogQueryWrapper.eq("report_id", reportId);
        if (CheckUtil.isNotNull(state)) {
            reportRecordLogQueryWrapper.eq("state", state);
        }
        reportRecordLogQueryWrapper.orderByAsc("sort");
        return ysShopReportRecordLogMapper.selectList(reportRecordLogQueryWrapper);
    }


    /**
     * 获取 居民 报表错误日志
     *
     * @param reportId 报表 id
     * @return List
     */
    public List<ExcelYsShopError> getExcelUserInfoError(Integer reportId) {
        List<ExcelYsShopError> excelUserInfoErrorList = new ArrayList<>();
        List<YsShopReportRecordLog> logList = getReportRecordLogList(reportId, 9);
        logList.forEach(errorLog -> {
            ExcelYsShopError excelUserInfoError = new ExcelYsShopError();
            //解密手机号 和证件号
            aesMyUtilDecrypt(errorLog);
            BeanUtils.copyProperties(errorLog, excelUserInfoError);
            excelUserInfoErrorList.add(excelUserInfoError);
        });
        return excelUserInfoErrorList;
    }


    /**
     * 获取 导出报表需要的数据
     *
     * @param reportId 报表 id
     * @return Map
     */
    public Map<String, Object> getErrorLogInfo(Integer reportId) {
        Map<String, Object> result = new HashMap<>(5);
        YsShopReportRecord msReportRecord = ysShopReportRecordMapper.selectById(reportId);
        String name = msReportRecord.getReportName().substring(0, msReportRecord.getReportName().indexOf("."));
        result.put("excelName", name);
        return result;
    }


    /**
     * 获取Excel导入记录列表
     *
     * @return Result
     */
    public Result<Object> getReportRecordList(ReportRecordPageVO vo) {
        QueryWrapper<YsShopReportRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        IPage<YsShopReportRecord> recordPage = ysShopReportRecordMapper.selectPage(new Page<>(vo.getCurrentPage(), vo.getPageSize()), queryWrapper);
        List<YsShopReportRecord> recordList = recordPage.getRecords();
        //转化数据
        transformReportRecordList(recordList);
        return ResultUtil.getPageDataSuccess(new PageDo<>(recordPage.getCurrent(), recordPage.getSize(), Integer.parseInt(recordPage.getTotal() + ""), recordList));
    }

    private void transformReportRecordList(List<YsShopReportRecord> recordList) {
        recordList.forEach(model -> {

            //获取成功或失败的数量
            model.setSuccessCount(getSuccessOrFailCount(model.getId(), 1));
            model.setFailCount(getSuccessOrFailCount(model.getId(), 9));

            //操作人员姓名
            if (CheckUtil.isNotNull(model.getOperationUserId())) {
                SysUser user = sysUserMapper.selectById(model.getOperationUserId());
                model.setSysUserName(CheckUtil.isNull(user) ? "" : user.getUserName());
            }
        });
    }


    /**
     * @param reportId 关联报表记录id(report_record)
     * @param state    1：成功 9：失败
     * @return count
     */
    private Integer getSuccessOrFailCount(Integer reportId, Integer state) {
        QueryWrapper<YsShopReportRecordLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("report_id", reportId);
        queryWrapper.eq("state", state);
        return ysShopReportRecordLogMapper.selectCount(queryWrapper);
    }


}
